// utils/request.js
import axios from 'axios';
import theme from './theme';

const testURL = 'http://47.122.70.37:8082/goods';
const testWeb = 'http://47.122.70.37:8088/index.html';
const zhangURL = 'http://47.122.26.94:8083/goods';
const zhangWeb = 'http://47.122.26.94:8089/index.html';
const huangURL = 'http://47.122.26.94:8082/goods';
const huangWeb = 'http://47.122.26.94:8088/index.html';

const instance = axios.create({
  baseURL:
    theme.app.name === '测试app'
      ? testURL
      : theme.app.name === '江楠韵'
      ? zhangURL
      : huangURL,
  timeout: 10000, // 请求超时时间
});

// 请求拦截器
instance.interceptors.request.use(
  async config => {
    // 如果是 FormData，设置请求头
    if (config.data instanceof FormData) {
      config.headers['Content-Type'] = 'multipart/form-data';
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  },
);

// 响应拦截器
instance.interceptors.response.use(
  response => {
    console.log('请求结果：', response.data);
    return response.data;
  },
  error => {
    return Promise.reject(error);
  },
);

/**
 * 封装 POST 请求
 * @param {string} url - 请求地址
 * @param {object} data - 请求体数据
 * @param {object} headers - 自定义请求头
 * @returns {Promise} - 返回解析后的响应数据
 */
export const post = (url, data = {}, headers = {}) => {
  // 获取 baseURL
  const baseURL = instance.defaults.baseURL;
  // 拼接完整的请求地址
  const fullURL = baseURL + url;
  console.log('请求地址：' + fullURL);
  let objNew = {};
  for (let i = 0; i < data._parts.length; i++) {
    const [key, value] = data._parts[i];
    objNew[key] = value;
  }
  console.log('请求参数：', objNew);
  return instance.post(url, data, {headers});
};

export default instance;
